﻿using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace LicenseApp.Producer;

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    // 应用程序路径获取 - 按要求实现
    public static string assemblyFilePath = System.Diagnostics.Process.GetCurrentProcess().MainModule?.FileName ?? "";
    public static string assemblyDirPath = System.IO.Path.GetDirectoryName(assemblyFilePath) ?? "";
    public static string PATH = assemblyDirPath;

    private string? currentCustomer;
    private string? currentLicenseCode;

    public MainWindow()
    {
        InitializeComponent();
        InitializeUI();
    }

    private void InitializeUI()
    {
        // 设置默认日期为今天
        dpStartDate.SelectedDate = DateTime.Today;

        // 刷新客户列表
        RefreshCustomerList();
    }

    private void RefreshCustomerList()
    {
        var customers = KeyManager.GetCustomers();
        cmbCustomers.ItemsSource = customers;

        if (customers.Count > 0)
        {
            cmbCustomers.SelectedIndex = 0;
        }
    }

    private void BtnGenerateKeys_Click(object sender, RoutedEventArgs e)
    {
        var customerName = txtNewCustomer.Text.Trim();

        if (string.IsNullOrEmpty(customerName))
        {
            MessageBox.Show("请输入客户名称", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
            return;
        }

        if (KeyManager.CustomerExists(customerName))
        {
            var result = MessageBox.Show($"客户 '{customerName}' 已存在密钥对，是否重新生成？",
                "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (result != MessageBoxResult.Yes)
                return;
        }

        if (KeyManager.GenerateKeyPair(customerName))
        {
            MessageBox.Show($"客户 '{customerName}' 的密钥对生成成功！", "成功",
                MessageBoxButton.OK, MessageBoxImage.Information);

            txtNewCustomer.Clear();
            RefreshCustomerList();

            // 自动选择新创建的客户
            cmbCustomers.SelectedItem = customerName;
        }
        else
        {
            MessageBox.Show("密钥对生成失败，请检查客户名称是否有效", "错误",
                MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    private void BtnRefreshCustomers_Click(object sender, RoutedEventArgs e)
    {
        RefreshCustomerList();
    }

    private void CmbCustomers_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        currentCustomer = cmbCustomers.SelectedItem as string;

        // 清空之前的授权码和测试结果
        txtLicenseCode.Clear();
        txtTestResult.Text = "";
        currentLicenseCode = null;

        // 更新客户授权状态显示
        UpdateCustomerLicenseStatus();
    }

    private void BtnGenerateLicense_Click(object sender, RoutedEventArgs e)
    {
        if (string.IsNullOrEmpty(currentCustomer))
        {
            MessageBox.Show("请先选择客户", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
            return;
        }

        if (!dpStartDate.SelectedDate.HasValue)
        {
            MessageBox.Show("请选择生效日期", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
            return;
        }

        if (!int.TryParse(txtDays.Text, out int days) || days <= 0)
        {
            MessageBox.Show("请输入有效的授权天数", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
            return;
        }

        if (!int.TryParse(txtAgvCount.Text, out int agvCount) || agvCount <= 0)
        {
            MessageBox.Show("请输入有效的AGV数量", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
            return;
        }

        // 获取机器码（可选）
        var machineCode = txtMachineCode.Text.Trim();

        // 验证机器码格式（如果提供了机器码）
        if (!string.IsNullOrEmpty(machineCode))
        {
            if (!IsValidMachineCodeFormat(machineCode))
            {
                MessageBox.Show("机器码格式不正确，应为 XXXX-XXXX-XXXX-XXXX 格式", "提示",
                              MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
        }

        var licenseCode = LicenseGenerator.GenerateLicense(currentCustomer, dpStartDate.SelectedDate.Value, days, agvCount, machineCode);

        if (!string.IsNullOrEmpty(licenseCode))
        {
            currentLicenseCode = licenseCode;
            txtLicenseCode.Text = licenseCode;

            var successMessage = "授权码生成成功！";
            if (!string.IsNullOrEmpty(machineCode))
            {
                successMessage += $"\n已绑定到机器码: {machineCode}";
            }
            else
            {
                successMessage += "\n未绑定机器码，可在任意机器使用";
            }

            MessageBox.Show(successMessage, "成功", MessageBoxButton.OK, MessageBoxImage.Information);

            // 更新客户授权状态显示
            UpdateCustomerLicenseStatus();
        }
        else
        {
            MessageBox.Show("授权码生成失败，请检查客户密钥是否存在", "错误",
                MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    private void BtnTestLicense_Click(object sender, RoutedEventArgs e)
    {
        if (string.IsNullOrEmpty(currentCustomer))
        {
            txtTestResult.Text = "错误：请先选择客户";
            txtTestResult.Foreground = new SolidColorBrush(Colors.Red);
            return;
        }

        if (string.IsNullOrEmpty(currentLicenseCode))
        {
            txtTestResult.Text = "错误：请先生成授权码";
            txtTestResult.Foreground = new SolidColorBrush(Colors.Red);
            return;
        }

        var (isValid, licenseData) = LicenseGenerator.ValidateLicense(currentCustomer, currentLicenseCode);

        if (isValid && licenseData != null)
        {
            var isActive = LicenseGenerator.IsLicenseActive(licenseData);
            var remainingDays = LicenseGenerator.GetRemainingDays(licenseData);

            var result = $"✓ 授权码验证成功\n" +
                        $"生效日期: {licenseData.StartDate}\n" +
                        $"授权天数: {licenseData.Days}\n" +
                        $"AGV数量: {licenseData.AgvCount}\n" +
                        $"当前状态: {(isActive ? "有效" : "无效")}\n" +
                        $"剩余天数: {(remainingDays >= 0 ? remainingDays.ToString() : "已过期")}";

            txtTestResult.Text = result;
            txtTestResult.Foreground = new SolidColorBrush(Colors.Green);
        }
        else
        {
            txtTestResult.Text = "✗ 授权码验证失败：签名无效或数据损坏";
            txtTestResult.Foreground = new SolidColorBrush(Colors.Red);
        }
    }

    private void BtnCopyLicense_Click(object sender, RoutedEventArgs e)
    {
        if (!string.IsNullOrEmpty(currentLicenseCode))
        {
            Clipboard.SetText(currentLicenseCode);
            MessageBox.Show("授权码已复制到剪贴板", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
        }
        else
        {
            MessageBox.Show("没有可复制的授权码", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
        }
    }

    // === 新增的界面功能 ===

    private void BtnOpenKeysFolder_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            string keysPath;

            if (!string.IsNullOrEmpty(currentCustomer))
            {
                // 如果选择了客户，打开客户专属目录
                keysPath = System.IO.Path.Combine(PATH, "Keys", currentCustomer);
                if (!System.IO.Directory.Exists(keysPath))
                {
                    keysPath = System.IO.Path.Combine(PATH, "Keys");
                }
            }
            else
            {
                // 否则打开Keys根目录
                keysPath = System.IO.Path.Combine(PATH, "Keys");
            }

            // 确保目录存在
            if (!System.IO.Directory.Exists(keysPath))
            {
                System.IO.Directory.CreateDirectory(keysPath);
            }

            // 打开文件资源管理器
            System.Diagnostics.Process.Start("explorer.exe", keysPath);
        }
        catch (Exception ex)
        {
            MessageBox.Show($"无法打开密钥目录: {ex.Message}", "错误",
                MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    private void BtnDaysUp_Click(object sender, RoutedEventArgs e)
    {
        if (int.TryParse(txtDays.Text, out int currentDays))
        {
            txtDays.Text = (currentDays + 1).ToString();
        }
    }

    private void BtnDaysDown_Click(object sender, RoutedEventArgs e)
    {
        if (int.TryParse(txtDays.Text, out int currentDays) && currentDays > 1)
        {
            txtDays.Text = (currentDays - 1).ToString();
        }
    }

    private void BtnQuickDays_Click(object sender, RoutedEventArgs e)
    {
        if (sender is Button button && button.Tag is string daysStr)
        {
            txtDays.Text = daysStr;
        }
    }

    /// <summary>
    /// 更新客户授权状态显示
    /// </summary>
    private void UpdateCustomerLicenseStatus()
    {
        if (string.IsNullOrEmpty(currentCustomer))
        {
            txtCustomerLicenseStatus.Text = "未选择客户";
            txtCustomerLicenseDetails.Text = "";
            btnClearCustomerLicense.IsEnabled = false;
            return;
        }

        // 检查客户是否有授权文件
        if (KeyManager.HasCustomerLicense(currentCustomer))
        {
            var licenseCode = KeyManager.GetCustomerLicenseCode(currentCustomer);
            if (!string.IsNullOrEmpty(licenseCode))
            {
                // 验证授权码并显示详细信息
                var (isValid, licenseData) = LicenseGenerator.ValidateLicense(currentCustomer, licenseCode);

                if (isValid && licenseData != null)
                {
                    var isActive = LicenseGenerator.IsLicenseActive(licenseData);
                    var remainingDays = LicenseGenerator.GetRemainingDays(licenseData);

                    // 设置状态文本和颜色
                    if (isActive)
                    {
                        txtCustomerLicenseStatus.Text = "✅ 有效授权";
                        txtCustomerLicenseStatus.Foreground = new SolidColorBrush(Colors.Green);
                    }
                    else
                    {
                        txtCustomerLicenseStatus.Text = "❌ 授权已过期";
                        txtCustomerLicenseStatus.Foreground = new SolidColorBrush(Colors.Red);
                    }

                    // 设置详细信息
                    var statusText = $"生效日期: {licenseData.StartDate} | " +
                                   $"授权天数: {licenseData.Days} | " +
                                   $"AGV数量: {licenseData.AgvCount} | " +
                                   $"剩余天数: {(remainingDays >= 0 ? remainingDays.ToString() : "已过期")}";

                    txtCustomerLicenseDetails.Text = statusText;
                }
                else
                {
                    txtCustomerLicenseStatus.Text = "⚠️ 授权码无效";
                    txtCustomerLicenseStatus.Foreground = new SolidColorBrush(Colors.Orange);
                    txtCustomerLicenseDetails.Text = "授权码格式错误或签名验证失败";
                }
            }
            else
            {
                txtCustomerLicenseStatus.Text = "⚠️ 读取授权失败";
                txtCustomerLicenseStatus.Foreground = new SolidColorBrush(Colors.Orange);
                txtCustomerLicenseDetails.Text = "无法读取授权文件内容";
            }

            btnClearCustomerLicense.IsEnabled = true;
        }
        else
        {
            txtCustomerLicenseStatus.Text = "🔒 未授权";
            txtCustomerLicenseStatus.Foreground = new SolidColorBrush(Colors.Gray);
            txtCustomerLicenseDetails.Text = "该客户尚未生成授权码";
            btnClearCustomerLicense.IsEnabled = false;
        }
    }

    /// <summary>
    /// 清除客户授权
    /// </summary>
    private void BtnClearCustomerLicense_Click(object sender, RoutedEventArgs e)
    {
        if (string.IsNullOrEmpty(currentCustomer))
        {
            MessageBox.Show("请先选择客户", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
            return;
        }

        var result = MessageBox.Show($"确定要清除客户 '{currentCustomer}' 的授权吗？\n\n此操作将删除该客户的 license.txt 文件。",
            "确认清除", MessageBoxButton.YesNo, MessageBoxImage.Question);

        if (result == MessageBoxResult.Yes)
        {
            if (KeyManager.ClearCustomerLicense(currentCustomer))
            {
                MessageBox.Show("客户授权已清除", "成功", MessageBoxButton.OK, MessageBoxImage.Information);

                // 更新状态显示
                UpdateCustomerLicenseStatus();

                // 清空当前授权码显示
                txtLicenseCode.Clear();
                txtTestResult.Text = "";
                currentLicenseCode = null;
            }
            else
            {
                MessageBox.Show("清除授权失败", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }

    /// <summary>
    /// 验证机器码格式是否正确
    /// </summary>
    /// <param name="machineCode">机器码</param>
    /// <returns>格式是否正确</returns>
    private bool IsValidMachineCodeFormat(string machineCode)
    {
        if (string.IsNullOrEmpty(machineCode))
            return false;

        // 验证格式：XXXX-XXXX-XXXX-XXXX
        // 机器码使用Base64字符集（去除+/=），包含A-Z、a-z、0-9
        var pattern = @"^[A-Za-z0-9]{4}-[A-Za-z0-9]{4}-[A-Za-z0-9]{4}-[A-Za-z0-9]{4}$";
        return System.Text.RegularExpressions.Regex.IsMatch(machineCode, pattern);
    }

    /// <summary>
    /// 保存授权码到文件
    /// </summary>
    private void BtnSaveLicense_Click(object sender, RoutedEventArgs e)
    {
        if (string.IsNullOrEmpty(currentLicenseCode))
        {
            MessageBox.Show("没有可保存的授权码，请先生成授权码", "提示",
                          MessageBoxButton.OK, MessageBoxImage.Warning);
            return;
        }

        if (string.IsNullOrEmpty(currentCustomer))
        {
            MessageBox.Show("请先选择客户", "提示",
                          MessageBoxButton.OK, MessageBoxImage.Warning);
            return;
        }

        try
        {
            // 创建带时间戳的文件名
            var timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss_fff");
            var fileName = $"license_{currentCustomer}_{timestamp}.txt";

            // 创建授权码保存目录
            var licenseDir = System.IO.Path.Combine(PATH, "LicenseCodes");
            if (!System.IO.Directory.Exists(licenseDir))
            {
                System.IO.Directory.CreateDirectory(licenseDir);
            }

            // 创建按日期分组的子目录
            var dateDir = System.IO.Path.Combine(licenseDir, DateTime.Now.ToString("yyyy-MM-dd"));
            if (!System.IO.Directory.Exists(dateDir))
            {
                System.IO.Directory.CreateDirectory(dateDir);
            }

            var filePath = System.IO.Path.Combine(dateDir, fileName);

            // 创建授权码文件内容
            var licenseInfo = CreateLicenseFileContent();

            // 保存到文件
            System.IO.File.WriteAllText(filePath, licenseInfo, Encoding.UTF8);

            // 显示成功消息
            var message = $"授权码已保存到文件：\n\n{filePath}\n\n是否打开文件所在目录？";
            var result = MessageBox.Show(message, "保存成功",
                                       MessageBoxButton.YesNo, MessageBoxImage.Information);

            if (result == MessageBoxResult.Yes)
            {
                // 打开文件所在目录
                System.Diagnostics.Process.Start("explorer.exe", $"/select,\"{filePath}\"");
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show($"保存授权码文件失败：\n\n{ex.Message}", "错误",
                          MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    /// <summary>
    /// 创建授权码文件内容
    /// </summary>
    private string CreateLicenseFileContent()
    {
        var sb = new StringBuilder();

        // 文件头信息
        sb.AppendLine("# 授权码文件");
        sb.AppendLine($"# 生成时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}");
        sb.AppendLine($"# 客户名称: {currentCustomer}");
        sb.AppendLine($"# 生效日期: {dpStartDate.SelectedDate?.ToString("yyyy-MM-dd")}");
        sb.AppendLine($"# 授权天数: {txtDays.Text}");
        sb.AppendLine($"# AGV数量: {txtAgvCount.Text}");

        var machineCode = txtMachineCode.Text.Trim();
        if (!string.IsNullOrEmpty(machineCode))
        {
            sb.AppendLine($"# 绑定机器码: {machineCode}");
        }
        else
        {
            sb.AppendLine("# 绑定机器码: 未绑定（可在任意机器使用）");
        }

        sb.AppendLine("#");
        sb.AppendLine("# 使用说明：");
        sb.AppendLine("# 1. 复制授权码内容，通过客户端程序的授权注册界面输入");
        sb.AppendLine("# 2. 或者将此文件内容（Base64授权码）直接发送给客户");
        sb.AppendLine("# 3. 客户通过程序界面输入授权码完成注册");
        sb.AppendLine("#");
        sb.AppendLine();

        // 授权码内容
        sb.AppendLine("# === 授权码内容 ===");
        sb.AppendLine(currentLicenseCode);

        return sb.ToString();
    }
}